package com.cmol.peopledetectapp.user;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.cmol.data.GlobalData;
import com.cmol.data.Host;
import com.cmol.data.SettingData;
import com.cmol.net.Network;
import com.cmol.peopledetectapp.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.Proxy;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 场景详细信息
 *
 * @author 张瀚文 王国良
 */
public class DetailActivity extends AppCompatActivity {
    // 小数格式转换
    DecimalFormat decimalFormat = new DecimalFormat("##.0%");
    private TextView title, currentNumText, currentSeatText, seatRateText, currentNum, currentSeatNum, currentRate, PoiName;
    private Network network;
    private List<com.cmol.peopledetectapp.json.Scene> sceneList;
    private View view;
    private String peo = new String("");
    private String set = new String("");
    private Double cSet = new Double(0);
    private Double occ = new Double(0);
    private String isOpen = new String("");
    private String plaName = new String("");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detal);
        view = findViewById(R.id.DetialBackground);
        title = findViewById(R.id.textView14);

        // 提示标签
        PoiName = findViewById(R.id.textView14);
        currentNumText = findViewById(R.id.textView15);
        currentSeatText = findViewById(R.id.textView17);
        seatRateText = findViewById(R.id.textView20);

        // 数据内容标签
        currentNum = findViewById(R.id.currentPeople2);
        currentSeatNum = findViewById(R.id.currentSeat);
        currentRate = findViewById(R.id.occupancy2);

        /**
         * 根据系统设置修改界面
         * 通信，初始化界面信息
         */
        SystemSetting();
        Init1();
    }

    /**
     * 系统设置
     */
    private void SystemSetting() {
        // 判断中/英文
        if (SettingData.getLANGUAGE() == false) {
            currentNumText.setText("Current Num");
            currentSeatText.setText("Current Seats");
            seatRateText.setText("Vacancy Rate");
        } else {
            currentNumText.setText("当前人数");
            currentSeatText.setText("当前空座位数");
            seatRateText.setText("占座率");
        }

        // 判断主题
        if (SettingData.getCOLOR() == false) {
            view.setBackgroundResource(R.drawable.redbackground);
        } else {
            view.setBackgroundResource(R.drawable.background_iner);
        }
    }

    // 通信测试
    private void Init1() {
//        String peo
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .proxy(Proxy.NO_PROXY)
                .build();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("id", String.valueOf(GlobalData.getCurrentSceneID()));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
        RequestBody requestBody = RequestBody.create(mediaType, "" + jsonObject.toString());
        Request request = new Request.Builder()
                .url(Host.host + "/user/sceneCheck")
                .addHeader("Authorization", GlobalData.getUserToken())
                .post(requestBody)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            /**
             * Called when the request could not be executed due to cancellation, a connectivity problem or
             * timeout. Because networks can fail during an exchange, it is possible that the remote server
             * accepted the request before the failure.
             *
             * @param call
             * @param e
             */
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("==============body:", e.toString());
                        Toast.makeText(DetailActivity.this, "网络请求异常", Toast.LENGTH_SHORT).show();
                    }
                });
            }


            /**
             * Called when the HTTP response was successfully returned by the remote server. The callback may
             * proceed to read the response body with . The response is still live until
             * its response body is {@linkplain ResponseBody closed}. The recipient of the callback may
             * consume the response body on another thread.
             *
             * <p>Note that transport-layer success (receiving a HTTP response code, headers and body) does
             * not necessarily indicate application-layer success: {@code response} may still indicate an
             * unhappy HTTP response code like 404 or 500.
             *
             * @param call
             * @param response
             */
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String res = Objects.requireNonNull(response.body()).string().trim();
                Log.e("=====================res", response.toString());
                Log.e("====body: ", res);
                Log.e("========================code ", String.valueOf(response.code()));
                if (response.code() == 200) {
                    try {
//                        final String body = Objects.requireNonNull(response.body()).string().trim();
                        JSONObject json = new JSONObject(res);
                        Log.e("result:===========", json.toString());
                        JSONObject array = json.getJSONObject("scene");
                        Log.e("array==============================", array.toString());

                        peo = array.getString("peopleNum");
                        set = array.getString("seatNum");
                        isOpen = array.getString("open");
                        plaName = array.getString("name");
                        cSet = Double.valueOf(set) - Double.valueOf(peo);
                        occ = Double.valueOf(peo) / Double.valueOf(set);
                        Log.e("occ++++++++++++++++++++++", occ.toString());

//                        Log.e("peo", peo.toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            }
        });
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        /**
         * 内容设定
         */
        PoiName.setText(plaName);

        if (isOpen.equals("true")) {
            currentNum.setText(peo + "人");
            currentSeatNum.setText(cSet.toString() + "座位");
            currentRate.setText(decimalFormat.format(occ).toString());
        } else {
            currentNum.setText("无权访问");
            currentNum.setTextColor(0xffff0000);
            currentSeatNum.setText("无权访问");
            currentSeatNum.setTextColor(0xffff0000);
            currentRate.setText("无权访问");
            currentRate.setTextColor(0xffff0000);
        }
    }
}